package com.example.test.domain;

import com.example.test.annotation.RequestView;
import com.example.test.domain.group.request.Query;
import com.example.test.domain.group.validation.Create;
import com.example.test.domain.group.validation.Update;
import com.example.test.domain.group.json.BaseView;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.Date;
import java.util.Set;

/**
 * 用户
 */
@EqualsAndHashCode(callSuper = true)
@Entity
@Data
public class User extends Base implements UserDetails {
    /**
     * 用户名
     */
    @Column(unique = true, nullable = false)
    @NotNull(groups = {Create.class, Update.class})
    @JsonView({BaseView.class})
    @RequestView({Query.class})
    private String username;

    /**
     * 密码
     */
    @JsonIgnore
    private String password;

    /**
     * 昵称
     */
    @JsonView({BaseView.class})
    private String nickname;

    /**
     * 角色列表
     */
    @JsonIgnore
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Role> roles;

    /**
     * 账户过期时间
     */
    private Date expirationDate;

    /**
     * 账户锁定状态
     */
    private Boolean locked;

    /**
     * 证书过期时间(密码过期时间)
     */
    private Date credentialsExpirationDate;

    /**
     * 启用状态
     */
    private Boolean enabled;

    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        if(expirationDate == null){
            return true;
        }else{
            return expirationDate.getTime() > System.currentTimeMillis();
        }
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return locked == null || !locked;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        if(credentialsExpirationDate == null){
            return true;
        }else{
            return credentialsExpirationDate.getTime() > System.currentTimeMillis();
        }
    }

    @Override
    public boolean isEnabled() {
        return enabled == null ? true : enabled;
    }
}
